package com.ergou.easylive.admin.config;

import com.ergou.easylive.admin.properties.CacheProperties;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;

/**
 * 缓存配置
 *
 * @author Er-Gou
 * @date 2025-09-16 23:30
 */
@Configuration
@EnableCaching
public class CacheConfig {

    @Resource
    private CacheProperties cacheProperties;

    /**
     * 配置缓存管理器 - 使用Caffeine实现过期时间
     *
     * @return CacheManager
     */
    @Bean
    public CacheManager cacheManager() {
        // 创建Caffeine缓存配置
        Caffeine<Object, Object> caffeine = Caffeine.newBuilder()
                // 验证码缓存过期时间（从配置文件读取）
                .expireAfterWrite(Duration.ofMinutes(cacheProperties.getCaptchaExpireMinutes()))
                // 最大缓存条目数（从配置文件读取）
                .maximumSize(cacheProperties.getCaptchaMaxSize());

        // 如果启用统计，则添加统计功能
        Caffeine<Object, Object> caffeineToUse = cacheProperties.isEnableStats() 
                ? caffeine.recordStats() 
                : caffeine;

        // 创建Caffeine缓存管理器
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
        cacheManager.setCaffeine(caffeineToUse);
        
        // 设置缓存名称
        cacheManager.setCacheNames(Collections.singletonList("captcha"));
        
        return cacheManager;
    }
}
